//开始点和结束点
var beginLocation = [];
var endLocation = [];
var isSelectRegion = false;
var isSelectRegionIng = false;
var isSelectBegin = true;
var zoneTemp = null;
var beginZoneList = [];
var endZoneList = [];


// var beginInput = document.getElementById("beginLocationInput");
// var endInput = document.getElementById("endLocationInput");

var colorList = {
    c0: "rgb(0,0,255)"
    , c1: "rgb(0,150,250)"
    , c2: "rgb(0,200,200)"
    , c3: "rgb(0,250,100)"
    , c4: "rgb(50,255,50)"
    , c5: "rgb(100,255,0)"
    , c6: "rgb(150,255,0)"
    , c7: "rgb(255,230,0)"
    , cmax: "#ff0000"
};

var colorArr = ["#1E90FF", "#ff33ff", "#993333", "#3333ff", "#ff6600", "#003333", "#660033"];

var corrections = [
    {
        name: "B01",
        text: "干燥仓"
    }
    , {
        name: "B11",
        text: "烟煤仓"
    }
    , {
        name: "B21",
        text: "1#仓"
    }
    , {
        name: "B22",
        text: "2#仓"

    }
    , {
        name: "B23",
        text: "3#仓"

    }
    , {
        name: "B24",
        text: "4#仓"

    }
    , {
        name: "B25",
        text: "5#仓"

    }
    , {
        name: "B26",
        text: "6#仓"

    }
    , {
        name: "B27",
        text: "7#仓"

    }
    , {
        name: "B28",
        text: "8#仓"

    }
    , {
        name: "B29",
        text: "9#仓"

    }
    , {
        name: "B30",
        text: "10#仓"
    }
    , {
        name: "B31",
        text: "11#仓"

    }
    , {
        name: "B32",
        text: "12#仓"
    }

];

var outportMap = [];
var cellMap = [];
var cellLocations = [];


var cellCanvas = document.getElementById("cellcanvas");
var cellCanvasCtx = cellCanvas.getContext('2d');

// var CXL = {
//     ctxPath: "",
//     addCtx: function (ctx) {
//         if (this.ctxPath === "") {
//             this.ctxPath = ctx;
//         }
//     }
// };
// <script src="${ctxPath}/layuiadmin/layui/layui.js"></script>
layui.config({
    base: '${ctxPath}/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index' //主入口模块
}).use(['index', 'form', 'layer', 'table'], function () {

    form = layui.form;
    let element = layui.element;
    let router = layui.router();
    var table = layui.table;
    let resetButton = document.getElementById("resetButton");
    $ = layui.$;

    initMap();

    // updateActionTable(null);

    cellCanvas.addEventListener("click", areaClickCanvas);

    form.on('radio(isSelectBegin)', function (data) {
        console.log(typeof (data.value));
        if (data.value == "true") {
            isSelectBegin = true;
        } else {
            isSelectBegin = false;
        }
        if (isSelectBegin) {
            layer.msg("当前请选择起始点");
        } else {
            layer.msg("当前请选择终点");
        }
    });

    form.on('radio(ChoiceRadio)', function (data) {

        if (data.value == "1") {
            isSelectRegion = true;
        } else {
            isSelectRegion = false;
        }

    });

    Object.defineProperty(beginLocation, 'data', {
        get: function () {
            return data;
        },
        set: function (newValue) {
            data = newValue;
            console.log('set :', newValue);
            $('beginLocationInput').textbox('setValue', newValue);
            //需要触发的渲染函数可以写在这...
        }
    });

    /**
     * 表格参数
     */
    var Page = {
        tableId: 'actionTable',
        url: '/boot/semiautomaticway/datagrid',
        toolbar: '#table-toolbar',
        // where:{field:'createDate', order:'desc'},
        initColumn: function () {
            return [[
                // {type: 'numbers'},
                {field: 'id', title: 'ID', width: 80}
                , {field: 'name', title: '动作名称', width: 150}
                , {field: 'beginLocation', title: '开始位置',hide:true, width: 150}
                , {field: 'endLocation', title: '结束位置', hide:true,width: 150}
                , {field: 'workMode', title: '工作模式', hide:true,width: 150}
                , {field: 'frequency', title: '运行次数', hide:true,width: 150}
                , {field: 'right', title: '操作', toolbar: '#table-toolbar', width: 115}
            ]];
        },
        deleteUrl: "/boot/semiautomaticway/delete"

    };


    /**
     * 表格的单击事件
     */
    Page.clickAction = function (obj) {

    }

    /**
     * 表格的双击事件
     */
    Page.doubleClickAction = function (obj) {

    }


    /**
     * 编辑
     */
    Page.openEdit = function (data) {
        layer.open({
            type: 2,
            title: '编辑',
            shadeClose: true,
            shade: 0.8,
            area: ['700px', '700px'],
            content: Page.addUrl + "?id=" + data.id,
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                //点击确认触发 iframe 内容中的按钮提交
                var submit = layero.find('iframe').contents().find("#form-btn-save");
                submit.click();

                //刷新表格
                Page.searchAction();
            }
        });
    };

    /**
     * 查看
     */
    Page.openDetail = function (data) {
        layer.open({
            type: 2,
            title: '查看',
            shadeClose: true,
            shade: 0.8,
            area: ['650px', '700px'],
            content: Page.addUrl + "?id=" + data.id
        });
    }

    /**
     * 删除表格数据
     */
    Page.deleteAction = function (obj) {
        parent.layer.confirm('真的确定要删除么', function (index) {

            //提交 Ajax进行后端删除
            $.ajax({
                type: "post",
                url: Page.deleteUrl,
                data: {id: obj.data.id},
                success: function (res) {
                    if (res.success) {
                        CXL.success(res.msg);
                        // layer.msg(res.msg);
                        //表格删除
                        obj.del();
                    } else {
                        CXL.warn(res.msg);
                        // layer.msg(res.msg);
                    }
                }
            });

            layer.close(index);
        });
    }

    /**
     * 加载表格数据
     */
    Page.loadAction = function (obj) {


        var begin = eval(obj.data.beginLocation);
        var end = eval(obj.data.endLocation);
        let workMode = obj.data.workMode;
        let frequency = obj.data.frequency;
        let name = obj.data.name;

        for (var index in begin) {
            // addLocation(begin[index], beginLocation, colorList.c5);
            for (let item1 of cellMap) {
                if (begin[index].name == item1.name) {
                    addLocation(item1, beginLocation, colorList.c5)
                }
            }
            for (let item1 of outportMap) {
                if (begin[index].name == item1.name) {
                    beginZoneList.push(item1.zoneId);
                    addLocation(item1, beginLocation, colorList.c5)
                }
            }

        }
        for (var index in end) {
            for (let item1 of cellMap) {
                if (end[index].name == item1.name) {
                    addLocation(item1, endLocation, colorList.c5)
                }
            }
            for (let item1 of outportMap) {
                if (end[index].name == item1.name) {
                    endZoneList.push(item1.zoneId);
                    addLocation(item1, endLocation, colorList.c5)
                }
            }
        }
        $('#box').val(2);
        drawCellMap();
    }


    /**
     * 表格渲染
     */
    table.render({
        elem: '#' + Page.tableId
        , url: Page.url
        // , height: 'full-140'
        , page: true
        , limit: 9
        , autoSort: false
        // , toolbar: Page.toolbar
        // , where: Page.where
        // , defaultToolbar: []

        , cols: Page.initColumn()
    });
    /**
     * 监听表格工具事件
     */
    // table.on('tool(' + Page.table-toolbar + ')', function (obj) {
    table.on('tool(actionTableRender)', function (obj) {
        //获得当前行数据
        var data = obj.data;
        //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var layEvent = obj.event;

        //查看操作
        if (layEvent === 'detail') {
            Page.openDetail(data);
        }
        //删除操作
        else if (layEvent === 'del') {
            Page.deleteAction(obj);
        }
        //删除操作
        else if (layEvent === 'load') {
            Page.loadAction(obj);
        }
        //编辑操作
        else if (layEvent === 'edit') {
            Page.openEdit(data);
        }
    });


    //监听行单击事件
    table.on('row(' + Page.tableId + ')', function (obj) {
        Page.clickAction(obj);
    });

    //监听行双击事件
    table.on('rowDouble(' + Page.tableId + ')', function (obj) {
        Page.doubleClickAction(obj);
    });

//提交
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form
            , layer = layui.layer

        form.on('submit(formDemo)', function (data) {
            var inputDataJson = JSON.stringify(data.field);
            var beginLocationJson = JSON.stringify(beginLocation);
            var endLocationJson = JSON.stringify(endLocation);
            $.ajax({
                url: "/boot/semiautomatic/postTask",
                data: {
                    craneId: 1,
                    inputData: inputDataJson,
                    beginLocationList: beginLocationJson,
                    endLocationList: endLocationJson,
                },
                type: "POST",
                dataType: "json",
                success: function (msg) {
                    console.log(msg)
                    layer.msg("任务提交成功！")
                },
                error: function (error) {
                    layer.msg("Error")
                }
            });
            return false;
        });


        form.on('submit(submitWay)', function (data) {
            var inputDataJson = JSON.stringify(data.field);
            var beginLocationJson = JSON.stringify(beginLocation);
            var endLocationJson = JSON.stringify(endLocation);
            $.ajax({
                url: "/boot/semiautomaticway/saveway",
                data: {
                    craneId: 1,
                    inputData: inputDataJson,
                    beginLocationList: beginLocationJson,
                    endLocationList: endLocationJson,
                },
                type: "POST",
                dataType: "json",
                success: function (msg) {
                    console.log(msg)
                    layer.msg("保存成功！")
                },
                error: function (error) {
                    layer.msg("Error")
                }
            });
            return false;
        });
    });

});




function initMap() {
    getCellMap();
    getOutputMap();
    initinfo();

    const results = GroupBy(cellMap, function (item) {
        return [item.zoneId];
    });
    // console.log(results.toString);
    drawCellMap(colorList.c1);
}

function getCellMap() {
    $.ajax({
        url: '/boot/wms/cell/getCellMap',
        type: 'get',
        async: false,
        dataType: 'json',
        data:
            {
                x1: 7400,
                x2: 66000,
                y1: 3200,
                y2: 29200,

            },

        success: function (data) {
            cellMap = data.cellMap;
            cellLocations = data.cellMap;

        }
    });
}

function getMaterial(){
    $.ajax({
        url: CXL.ctxPath + '/wms/materialtype/getdatalist',
        type: 'get',
        dataType: 'json',
        success: function (data) {
            $.each(data,function (index, item) {
                $('#materialTypeSelect').append(new Option(item.name, item.id));// 下拉菜单里添加元素
            });
            $('#materialTypeSelect').val($('#materialId')[0].value)
            form.render(null, 'layuiadmin-app-form-list');
        }
    });
}
function getOutputMap() {
    $.ajax({
        url: '/boot/wms/output/getOutputMap',
        type: 'get',
        async: false,
        dataType: 'json',
        data: {
            x1: 0,
            x2: 35000,
            y1: 0,
            y2: 12000
        },
        success: function (data) {
            outportMap = data.outputMap;
        }
    });
}

//默认参数初始化
function initinfo() {
    for (let item of cellMap) {
        item.topleftx = 1.5 * (item.x / 100);
        item.toplefty = 1.5 * (item.y / 100);
        item.lowerrightx = (item.topleftx + 15);
        item.lowerrighty = (item.toplefty + 15);
        item.color = colorArr[item.zoneId % 6];
    }
    //匹配上料仓名称
    for (let item of outportMap) {
        item["name"] = item.name;
        for (let item2 of corrections) {
            if (item.name === item2.name) {
                item["text"] = item2.text;

                item["zoneId"] = 3;
                item["color"] = colorArr[item.zoneId % 6];
                break;
            }
        }
    }

}

//绘制整个池子
function drawCellMap() {
    cellCanvasCtx.clearRect(0, 0, cellCanvas.width, cellCanvas.height);
    for (let item of cellMap) {
        drawRect(item.x / 100, item.y / 100, item.l / 100, item.w / 100, item.color);
    }


//绘制上料仓
    for (let item of outportMap) {
        drawText(cellCanvasCtx, (item.x / 100) * 1.5, (item.y / 100) * 1.5, "■", item.color, '60px "黑体"');

        drawText(cellCanvasCtx, (item.x / 100) * 1.5 + 5, (item.y / 100) * 1.5 + 40, item.text, 'gray', '23px "楷体"');
        // drawPoolInfo();
    }

}

//绘制一个矩形
function drawRect(x, y, l, w, color) {
    let ll = l / 2;
    let ww = w / 2;
    let xx = x - ll;
    let yy = y - ww;
    cellCanvasCtx.fillStyle = color;
    cellCanvasCtx.fillRect(1.5 * x - 100, 1.5 * y - 20, 1.5 * (l - 1), 1.5 * (l - 1));

}

function drawText(ctx, x, y, text, color, font) {
    ctx.fillStyle = color;
    ctx.font = font;
    ctx.fillText(text, x - 100, y - 20);
}

//池子点击监听
function areaClickCanvas(event) {
    let rect = cellCanvas.getBoundingClientRect();
    let x = event.clientX - rect.left * (cellCanvas.width / rect.width);
    let y = event.clientY - rect.top * (cellCanvas.height / rect.height);

    x += 100;
    y += 20;

    //检测是否选择区域

    if (isSelectRegion) {
        for (let item of cellMap) {
            if (x >= item.topleftx && x < item.lowerrightx && y >= item.toplefty && y < item.lowerrighty) {

                if (beginZoneList.indexOf(item.zoneId) > -1) {
                    if (isSelectBegin) {

                        for (let item1 of cellMap) {
                            if (item.zoneId == item1.zoneId) {
                                cancelSetLocation(item1, beginLocation);
                            }
                        }
                        deleteFromArrayByElement(beginZoneList, item.zoneId);
                        drawCellMap();

                    }
                } else if (endZoneList.indexOf(item.zoneId) > -1) {
                    if (!isSelectBegin) {
                        for (let item1 of cellMap) {
                            if (item.zoneId == item1.zoneId) {
                                cancelSetLocation(item1, endLocation);
                            }
                        }
                        deleteFromArrayByElement(endZoneList, item.zoneId);
                        drawCellMap();

                    } else {
                        alert("当前区域已作为结束区域！")
                    }
                } else {
                    // zoneList.push(item.zoneId);
                    addLocation(item, beginLocation, colorList.c5);
                    if (isSelectBegin) {
                        beginZoneList.push(item.zoneId);
                    } else {
                        endZoneList.push(item.zoneId);
                    }
                    for (let item1 of cellMap) {
                        if (item.zoneId == item1.zoneId) {
                            if (isSelectBegin) {
                                addLocation(item1, beginLocation, colorList.c5);

                            } else {
                                addLocation(item1, endLocation, colorList.cmax);
                            }
                        }
                    }

                    drawCellMap();

                }


            }

        }


    } else {
        for (let item of cellMap) {
            if (x >= item.topleftx && x < item.lowerrightx && y >= item.toplefty && y < item.lowerrighty) {

                if (item.color == colorList.c5 || item.color == colorList.cmax) {
                    cancelSetLocation(item);
                } else {
                    if (isSelectBegin) {
                        addLocation(item, beginLocation, colorList.c5);
                    } else {
                        addLocation(item, endLocation, colorList.cmax);
                    }

                }
                drawCellMap();
                break;
            }

        }
    }
//如果选择的是上料仓
    for (let item of outportMap) {
        let x1 = 1.5 * (item.x / 100)
        let x2 = 1.5 * (item.x / 100) + 60;
        let y1 = 1.5 * (item.y / 100)
        let y2 = 1.5 * (item.y / 100) + 60;

        if (x - xOffset >= x1 && x - xOffset <= x2 && y + 10 >= y1 && y + 10 <= y2) {
            if (item.color === colorArr[4]) {
                CXL.error("当前区域已被屏蔽！")
            } else if (item.color == colorList.c5) {
                cancelSetLocation(item, beginLocation);
                deleteFromArrayByElement(beginZoneList, item.zoneId);

            } else if (item.color == colorList.cmax) {
                cancelSetLocation(item, endLocations);
                deleteFromArrayByElement(endZoneList, item.zoneId);
            } else {
                if (isSelectBegin) {
                    CXL.warn("上料仓不能作为抓点！")
                } else if (!isSelectBegin) {
                    if(!checkIsPour()) {
                        addLocation(item, endLocations, colorList.cmax);
                    }else{
                        CXL.warn("倒料模式请勿选择上料仓作为放点！")
                    }
                }
            }
            drawCellMap(xOffset, yOffset)
            break;
        }
    }

}


//判断是否为倒料模式
function checkIsPour(){
    if($('input[name="selectWorkModel"]:checked').val() === "pour"){
        return true;
    }else{
        return false;
    }
}

//选择点
function addLocation(item, arr, color) {
    item.color = color;
    arr.push(item);
    // $("#beginLocationInput").attr("value","qqqqq");
    $("#beginLocationInput").val(beginLocation.toString());
    $("#endLocationInput").val(endLocation.toString());
    console.log(beginLocation);
    console.log(endLocation);

}

//取消选中
function cancelSetLocation(item, arr) {
    if (isSelectBegin) {
        item.color = colorArr[item.zoneId % 6];
        deleteFromArrayByElement(beginLocation, item);

        $("#beginLocationInput").val(beginLocation.toString());
        $("#endLocationInput").val(endLocation.toString());
        // beginInput.value = "";
    } else {
        item.color = colorArr[item.zoneId % 6];
        deleteFromArrayByElement(endLocation, item);

        $("#beginLocationInput").val(beginLocation.toString());
        $("#endLocationInput").val(endLocation.toString());
    }

}

//输出数组指定元素
function deleteFromArrayByElement(array, element) {
    array.forEach(function (item, index, arr) {
        if (item == element) {
            arr.splice(index, 1);
        }
    });
}

//分组元素
function GroupBy(array, fn) {
    // debugger;
    const groups = {};
    array.forEach(function (item) {
        const group = JSON.stringify(fn(item));
        groups[group] = groups[group] || [];
        groups[group].push(item);
    });
    return Object.keys(groups).map(function (group) {
        return groups[group];
    });
}
